package chan.module.project.comm;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.Set;

public class PropertiesUtil {
    private static final Logger LOG = LogManager.getLogger(PropertiesUtil.class);
    private Properties prop;

    public PropertiesUtil() {
    }

    public PropertiesUtil(String configPath) {
        loadConfig(configPath);
    }

    public static PropertiesUtil readConfig(String[] args) throws Exception {
        LOG.info("开始读取配置信息...");
        String configPath = null;
        for (String param : args) {
            if (param.startsWith("config=")) {
                configPath = param.replace("config=", "");
                break;
            }
        }
        if (configPath == null) {
            System.err.println("参数值[config]为空！");
            throw new Exception("参数值[config]为空！");
        }
        File configFile = new File(configPath);
        if (!configFile.exists()) {
            System.err.println("配置文件[" + configFile + "] 不存在！");
            throw new Exception("配置文件[" + configFile + "] 不存在！");
        }
        PropertiesUtil util = new PropertiesUtil();
        util.loadConfig(configPath);
        return util;
    }

    public PropertiesUtil loadConfig(String configPath) {
        prop = new Properties();
        try (InputStream input = new FileInputStream(configPath);
             InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) {
            prop.load(reader);
            System.out.println("配置信息列表：");
            print();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this;
    }

    public String get(String key) {
        return prop.getProperty(key);
    }

    public Properties getProp() {
        return prop;
    }


    public void print() {
        Set<String> strings = prop.stringPropertyNames();
        for (String key : strings) {
            LOG.info("config参数[{}]:{}", key, prop.getProperty(key));
        }
    }


}
